﻿/*
 { fields:[
  {
   name:'字段代码',
   text:'字段显示名称',
   ft:{},// form 字段配置  
   header:{}//表头的配置  
  }  
  ],
  url:'',// 表格加载url
  formConfig:{},
  windowConfig:{},
  gridConfig:{tbar:[]}
 }  
*/
(function(){

    function getFieldNames(fields)
    {
      var flds=[];
      fields=fields||[];
	  for(var i=0;i<fields.length;i++)
	  {
	    flds.push(fields[i].name);
	  }
	  return flds;
    }
    function getColumns(fields)
    {
      var cols=[];
      fields=fields||[];
	  for(var i=0;i<fields.length;i++)
	  {	    
	    cols.push(Ext.apply({header:fields[i].text, dataIndex: fields[i].name},fields[i].header));
	  }
	  return cols;     
    }
    function setTbar(tbar,scope)// scope for the handler
    {    
	  var item;	 
	  tbar=tbar||[];	  
	  if(!Ext.isArray(tbar)||tbar.length==0)return undefined;
	  for(var i=0;i<tbar.length;i++)
	  {
	    item=tbar[i];	   
	    if(typeof item.handler =="function")
	    {
          item.handler=(function(fn,text){ 
             return function(){                 
              fn.call(scope,text);
             }
          })(item.handler,item.text);        
	    }
	  }
	  return tbar;
    }   
    function setBbar(bbar,ds)
    {
       bbar=bbar||[];
       if(Ext.isArray(bbar))
       {
	       if(bbar.length==0)
	       {
	         return undefined;
	       }      
       }
       else
       {
         if(typeof bbar == 'object')
         {
           bbar= new Ext.PagingToolbar(Ext.apply({    
	        plugins:new Ext.ux.Andrie.pPageSize({variations:[10,15,20,25,30,50]}),     
	        pageSize: 10,
	        store:ds,
	        displayInfo: true
	       },bbar));
         }
         else
         {
            return undefined;
         }
       }

       return bbar;
    }
 
 
    
///*************************  end private method
	Ext.ns("Ext.fay.ui");
	
	Ext.fay.ui.CURDGrid=function(opt)
	{ 
	    this.initGrid(opt);
	    this.initFormWindow(opt);
	    this.addEvents("save");
	};
    Ext.extend(Ext.fay.ui.CURDGrid,Ext.util.Observable,{
	
	    initFormWindow:function(opt){
	  	 var mine=this;
	  	 var windowConfig=Ext.apply({
	  	 closable:true,   
		 closeAction:'hide',
	     width: 500,			
		 autoHeight: true,
		 resizable:true,
	     modal:true,	 
		 layout: 'fit',
		 border:false,
		 listeners:{hide:function(){mine.resetForm();}},
		 plain:true	},
		 opt.windowConfig);
	  	 
	  	 var formConfig=Ext.apply({
		 frame: true,
		 border:false,
		 autoHeight: true,
		 autoWidth:true,
		 waitMsgTarget: true,  
		 layout:'form',
		 defaultType:'textfield',
		 defaults: {anchor: '90%'},
		 buttons:[{text:' 保存 ',id:'submitButton',handler:function(){mine.fireEvent("save",mine.getValues())}}],
		 labelWidth:80	},
		 opt.formConfig);
		 
		 if(windowConfig.items)
		 {}
		 else
		 {
		   if(formConfig.items)
		   {}
		   else
		   {
		     formConfig.items=[];
		     var flds=opt.fields||[];
		     for(var i=0;i<flds.length;i++)
		     {
		       if(flds[i].isdata)continue;
		       var fconfig={name:flds[i].name,fieldLabel:flds[i].text};
		       var ft=flds[i].ft;
		       if(typeof ft == 'string' )
		       {
		         fconfig.xtype=ft;
		       }
		       else if(typeof ft == 'object' )
		       {
		         Ext.apply(fconfig,ft)
		       }
		       formConfig.items.push(fconfig)
		     }
		     //end for
		     if(formConfig.items.length==0)
		     {
		       formConfig.items.push({xtype:'label',value:'no field to display!'})
		     }	
		   }
		    this.form=new Ext.form.FormPanel(formConfig);
		    windowConfig.items=[this.form];		    	
		 }  	 
	     this.window=new Ext.Window(windowConfig);
	    }, 
	    initGrid:function(opt){
	        this.ds = new Ext.data.Store({
	            proxy: new Ext.data.HttpProxy({
	                method:'POST',
	                url: opt.url
	            }),
	            reader: new Ext.data.JsonReader({
	                root: 'root',
	                totalProperty: 'records',	
	                fields: getFieldNames(opt.fields)  
	            })		    
			});
			var sm = new Ext.grid.CheckboxSelectionModel({singleSelect:false});	
			var cols=[new Ext.grid.RowNumberer(),sm];
			var c_cols=getColumns(opt.fields);
			for(var i=0;i<c_cols.length;i++)
			{ 
			   cols.push(c_cols[i]);
			}		
			opt.gridConfig=opt.gridConfig||{};	
			opt.gridConfig.tbar=setTbar(opt.gridConfig.tbar,this);//override	
			opt.gridConfig.bbar=setBbar(opt.gridConfig.bbar,this.ds);//override	
			opt.gridConfig.listeners=opt.gridConfig.listeners||{};
			var mine=this;
			opt.gridConfig.listeners.beforedestroy=function(){
			  if(mine.window.el)
			  {
			     mine.window.destroy();
			  }
			}			
			this.grid=new Ext.grid.GridPanel(Ext.apply({
		    store: this.ds,
		    stripeRows: true,		 
            loadMask: true,
            border: false,
            sm:sm,
            viewConfig:{autoFill:true},          
            columns: cols          
            },opt.gridConfig));	    
	    },
	    setSubmitButton:function(fn){
	      var bt=this.bt||Ext.getCmp("submitButton");
	      if(bt)
	      {
	         bt[fn]();
	      }
	    },
	    resetForm:function()
	    {
		 try{  
			  this.window.hide();
			  this.form.getForm().reset();
			}catch(e){}	    
	    },	        
	    postJson:function(opt)
	    {
               
	         var mine=this;
	         this.setSubmitButton("disable");
	         Ext.Ajax.request({
		         method:'POST',
				 url:opt.url,				
				 success: function(res){	
				 	var data=Ext.util.JSON.decode(res.responseText);
				 	if(opt.callback)
				 	{
				 	  if(opt.callback.call(mine,data)===false)
				 	  {
				 	    return;
				 	  }
				 	}
				 	if(data.success)
				 	{
				 	  Ext.alert(data.info);
				 	} 
				 	else
				 	{
				 	  Ext.error(data.info);
				 	}
                    mine.setSubmitButton("enable");
				 	mine.ds.reload();	
				 	mine.resetForm();
				 },
				 failure: function(){
			        Ext.error("出错了");
	                this.setSubmitButton("enable");
				 },
				 jsonData:opt.params
		     });  
	    },
	    getValues:function(){
	     if(this.form) return this.form.getForm().getValues();
	     else return {};
	    },
	    isValid:function(){
	     if(this.form) return this.form.getForm().isValid();
	     else return false;
	    },	    
	    hasSelection:function()
	    {
	      return this.grid.getSelectionModel().hasSelection();
	    },
	    getSelection:function()
	    {
	      return this.grid.getSelectionModel().getSelected();
	    },      
	    getSelections:function()
	    {
	      return this.grid.getSelectionModel().getSelections();
	    },
        edit:function(){    
		    if(this.hasSelection())
		    {
			    this.window.show();
			    this.form.getForm().loadRecord(this.getSelection());
		    }
		    else
		    {
		       Ext.alert('请选择一行记录');      
		    }
	    },
	    del:function(fn)
	    {
	        var mine=this;      
	        if(this.hasSelection())
	        {
	           var r=this.getSelection();      
	           Ext.confirm('你确认删除吗？',function(bt){     
	            if(bt=="no")return;  
	            if(typeof fn =='function')fn.call(mine,mine.getSelections());
	           });
	        }
	        else
	        {        
	           Ext.alert('请选择一行记录');        
	        } 	    
	    }  
	});

})();